package org.lisy.java.cyclic;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 循环结构
 * 
 * @author lisy
 */
public class LoopStatement {
	
	/**
	 * 循环中删除防止ConcurrentModificationException异常
	 * 单线程:
	 *  1. 使用 for 循环
	 *  2. 增强 for 循环，删除元素时 break
	 *  3. 使用 Stream 的 filter 方法
	 *  4. 使用 iterator 迭代的 remove 方法
	 * 多线程:
	 *  1. 使用并发容器CopyOnWriteArrayList，可变操作是通过对底层数组进行一次新的复制来实现的
	 * 注意: 果获取了迭代器之后再对 CopyOnWriteArrayList 进行写操作，迭代器不能感知到这种变化
	 */
	public static void main(String[] args) {
		// for 循环
		int count = 0;
		for (int i = 0; i < 100; i++) {
			count += i + 1;
		}
		System.out.println(count);
		
		// 迭代器遍历
		String[] strings = {"A", "B", "C", "D"};
		Collection<String> stringList = Arrays.asList(strings);
		for (Iterator<String> itr = stringList.iterator(); itr.hasNext();) {
			Object str = itr.next();
			System.out.print(str + " ");
		}
		System.out.println("");
		
		// 增强 for 循环(声明语句:表达式)
		count = 0;
		int[] integers = {1, 2, 3, 4};
		for (final int i : integers) { // final禁止重复赋值
			count += i;
		}
		System.out.println(count);
		
		// Stream 遍历
		List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
        list.stream().forEach(i -> {
        	System.out.print(i + " ");
        });
        System.out.println();
		
		// switch 循环
		int num = 2;
		switch (num) {
			case 1:
				System.out.println("one");
				break;
			case 2:
				System.out.println("two");
			case 3:
			case 4:	
				System.out.println("three");
				break;
			default:
				System.out.println("none");
				break;
		}
		
		// while 循环
		int time = 0;
		count = 0;
		while (true){
			if (time == 100) {
				break;
			}
			time++;
			count += time;
		}
		System.out.println(count);
		
		// do while 循环
		int condtion = 0;
		count = 0;
		do {
			condtion++;
			if (condtion == 50) {
				continue;
			}
			count += condtion;
		} while (condtion < 100);
		System.out.println(count);
	}
}
